import 'dart:ffi';

import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_rider/generated/assets.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/kit/loc_kit.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/pop/pop_car_keyboard.dart';
import 'package:flutter_rider/main/widgets/pop/pop_outside_detail.dart';
import 'package:flutter_rider/main/widgets/state/refreshable_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/module/mine/models/truck_model.dart';
import 'package:flutter_rider/module/mine/provider/number_car_provider.dart';
import 'package:flutter_rider/module/mine/provider/outside_car_provider.dart';
import 'package:flutter_rider/module/mine/widgets/image_text_widget.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/main/widgets/dialog/bottom_sheet.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/config.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';

class OutsideCarDetailPage extends ConsumerStatefulWidget {
  final bool isAddCar;
  TruckModel? truck;
  OutsideCarDetailPage(this.isAddCar, {this.truck, Key? key}) : super(key: key);

  @override
  ConsumerState<OutsideCarDetailPage> createState() =>
      _OutsideCarDetailPageState();
}

class _OutsideCarDetailPageState extends ConsumerState<OutsideCarDetailPage> {
  var initMarkerMap = <String, Marker>{};
  //选中的位置
  late LatLng _position;
  AMapController? _mapController;
  @override
  void initState() {
    super.initState();
    if (widget.truck != null) {
      ref.read(numberCarProvider.notifier).assignNumber(widget.truck!.plate_no);
      ref.read(stopStationProvider).name = widget.truck!.park_name;
    }

    Future.delayed(const Duration(milliseconds: 500), () {
      if (widget.isAddCar) {
        OpenUtils.popKey(context, const CarKeyboard());
      }
      ref.read(positionProvider.state).state = _position;
      Log.i("获取到的定位信息-------> ${ref.read(positionProvider)}");
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _mapController?.disponse();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UIColor.color_main,
      body: SafeArea(
          top: false,
          bottom: false,
          // child: SizedBox(
          //     height: ScreenUtil.getInstance().screenHeight,
          //     width: ScreenUtil.getInstance().screenWidth,
          // child: SingleChildScrollView(
          // child: IntrinsicHeight(
          child: KeyboardDismissOnTap(
              dismissOnCapturedTaps: true,
              child: Column(
                children: [
                  Expanded(
                    flex: 1,
                    child: Stack(
                      children: [
                        _renderMap(),
                        widget.isAddCar
                            ? Padding(
                                padding: EdgeInsets.only(bottom: 20.rpx),
                                child: Align(
                                    alignment: Alignment.center,
                                    child: Image.asset(
                                      Assets.imageComponent,
                                      height: 40.rpx,
                                      width: 24.rpx,
                                    )))
                            : ScreenFit.empty,
                        Positioned(
                            bottom: 10.rpx,
                            right: 10.rpx,
                            child: widget.isAddCar
                                ? _renderResetLoc()
                                : _renderNavigate()),
                      ],
                    ),
                  ),
                  Expanded(
                      flex: 2,
                      child: OutsideDetailWidget(
                        widget.isAddCar,
                        truck: widget.truck,
                      )),
                  // const Positioned(
                  //     left: 0, right: 0, bottom: 0, child: CarKeyboard()),
                ],
              ))),
    );
  }

  // @override
  // Widget build(BuildContext context) {
  //   return Scaffold(
  //     backgroundColor: UIColor.color_main,
  //     body: SafeArea(
  //         top: false,
  //         bottom: false,
  //         child: KeyboardDismissOnTap(
  //             dismissOnCapturedTaps: true,
  //             child: CustomScrollView(
  //               slivers: [
  //                 _buildSliverAppBar(),
  //                 // SliverToBoxAdapter(
  //                 //   child: Container(height: 200, child: _renderMap()),
  //                 // ),
  //                 SliverToBoxAdapter(
  //                   child: OutsideDetailWidget(
  //                     widget.isAddCar,
  //                     truck: widget.truck,
  //                   ),
  //                 )
  //               ],
  //             ))),
  //   );
  // }

  // @override
  // Widget build(BuildContext context) {
  //   return Scaffold(
  //     backgroundColor: UIColor.color_main,
  //     body: SafeArea(
  //         top: false,
  //         bottom: false,
  //         child: KeyboardDismissOnTap(
  //             dismissOnCapturedTaps: true,
  //             child: NestedScrollView(
  //               headerSliverBuilder:
  //                   (BuildContext context, bool boxIsScrolled) {
  //                 boxIsScrolled = false;
  //                 return <Widget>[
  //                   _buildSliverAppBar(),
  //                 ];
  //               },
  //               body: OutsideDetailWidget(
  //                 widget.isAddCar,
  //                 truck: widget.truck,
  //               ),
  //             ))),
  //   );
  // }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
        pinned: false,
        snap: false,
        floating: false,
        // stretch: true,
        expandedHeight: ScreenUtil.getInstance().screenHeight / 3,
        flexibleSpace: FlexibleSpaceBar(
          // title: Text('车辆详情'),
          background: Stack(
            children: [
              _renderMap(),
              widget.isAddCar
                  ? Padding(
                      padding: EdgeInsets.only(bottom: 20.rpx),
                      child: Align(
                          alignment: Alignment.center,
                          child: Image.asset(
                            Assets.imageComponent,
                            height: 40.rpx,
                            width: 24.rpx,
                          )))
                  : ScreenFit.empty,
              Positioned(
                  bottom: 10.rpx,
                  right: 10.rpx,
                  child:
                      widget.isAddCar ? _renderResetLoc() : _renderNavigate()),
            ],
          ),
        ));
  }

  Widget _renderMap() {
    var initMarkerMap = <String, Marker>{};
    var lat = "0.0";
    var lng = "0.0";
    if (widget.truck == null) {
      var result = LocKit.instance.getData();
      if (result.containsKey('latitude') && result.containsKey('longitude')) {
        lat = result["latitude"].toString();
        lng = result["longitude"].toString();
        _position = LatLng(double.parse(lat), double.parse(lng));
      } else {
        _position = const LatLng(0, 0);
      }
    } else {
      lat = widget.truck!.lat;
      lng = widget.truck!.lng;
      _position = LatLng(
          double.parse(widget.truck!.lat), double.parse(widget.truck!.lng));
      var marker = Marker(
          position: _position,
          icon: BitmapDescriptor.fromIconPath(Assets.imageComponent),
          infoWindow: InfoWindow(title: "lat：$lat", snippet: "lng：$lng"),
          infoWindowEnable: true,
          onTap: (e) {});

      initMarkerMap[marker.id] = marker;
    }

    return AMapWidget(
      apiKey: const AMapApiKey(
          androidKey: Config.androidAmapKey, iosKey: Config.iOSAmapKey),
      onMapCreated: _onMapCreated,
      privacyStatement: const AMapPrivacyStatement(
          hasContains: true, hasShow: true, hasAgree: true),
      initialCameraPosition: CameraPosition(target: _position),
      // initialCameraPosition:
      //     CameraPosition(target: LatLng(22.532840, 113.946682)),

      markers: Set<Marker>.of(initMarkerMap.values),
      // polylines: Set<Polyline>.of(_polylines.values),
      buildingsEnabled: false,
      labelsEnabled: false,
      scrollGesturesEnabled: widget.isAddCar,
      myLocationStyleOptions: widget.isAddCar
          ? MyLocationStyleOptions(
              true,
              circleFillColor: Colors.transparent,
              circleStrokeColor: Colors.blue,
              circleStrokeWidth: 1,
              //根据输入的icon路径[iconPath]创建[BitmapDescriptor]定位小蓝点
              // icon: BitmapDescriptor.fromIconPath("assets/images/****.png"),
            )
          : null,
      // onCameraMove: (position) {
      //   Log.i(position.toString());
      // },
      onCameraMoveEnd: (position) {
        // Log.i("移动到的新位置---->${position.toString()}");
        _position = position.target;
        ref.read(positionProvider.state).state = _position;
        Log.i("获取到的定位信息-------> ${ref.read(positionProvider)}");
      },
    );
  }

  _onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
      _moveToPosition();
    });
  }

  _moveToPosition() {
    LatLng position;
    var lat = "0.0";
    var lng = "0.0";
    if (widget.truck == null) {
      var result = LocKit.instance.getData();
      if (result.containsKey('latitude') && result.containsKey('longitude')) {
        lat = result["latitude"].toString();
        lng = result["longitude"].toString();
        position = LatLng(double.parse(lat), double.parse(lng));
      } else {
        position = const LatLng(0, 0);
      }
    } else {
      lat = widget.truck!.lat;
      lng = widget.truck!.lng;
      position = LatLng(
          double.parse(widget.truck!.lat), double.parse(widget.truck!.lng));
    }

    _mapController?.moveCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(target: position, zoom: 16, tilt: 0, bearing: 0),
      ),
      animated: true,
    );
  }

  Widget _renderResetLoc() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        GestureDetector(
          onTap: () {
            setState(() {});
            _moveToPosition();
          },
          child: Container(
            padding: EdgeInsets.all(10.rpx),
            decoration: BoxDecoration(
              color: UIColor.color_content,
              borderRadius: BorderRadius.all(Radius.circular(8.rpx)),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.my_location_sharp,
                    size: 24.rpx, color: const Color(0xff54BD95)),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _renderNavigate() {
    return Container(
        padding: EdgeInsets.all(10.rpx),
        decoration: BoxDecoration(
          color: UIColor.color_content,
          borderRadius: BorderRadius.all(Radius.circular(8.rpx)),
        ),
        child: ImageTextWidget("导航", Assets.imageDirectUp,
            pixel: 24.rpx, valueColor: UIColor.color_primary, onTap: (() {
          var latLng = LatLng(
              double.parse(widget.truck!.lat), double.parse(widget.truck!.lng));
          OpenUtils.pop4(
              context,
              BottomSheetDialog(
                txAction: () {
                  LocKit.openTencentMap(latLng);
                },
                gdAction: () {
                  LocKit.openAmap(latLng);
                },
              ));
        })));
  }
}
